// components/search/index.js
import {
  KeywordModel
} from '../../models/keyword.js'
import {
  BookModel
} from '../../models/book.js'
import {
  paginationBev
} from '../behaviors/pagination.js'

const keywordModel = new KeywordModel()
const bookModel = new BookModel()

Component({
  /**
   * 组件的属性列表
   */
  behaviors: [paginationBev],
  properties: {
    more: {
      type: String,
      observer: 'loadMore'
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    historyWords: [],
    hotWords: [],
    searching: false,
    q: '',
    loadingCenter: false
  },

  attached() {
    this.setData({
      historyWords: keywordModel.getHistoryWord()
    })

    keywordModel.getHot().then((res) => {
      this.setData({
        hotWords: res.hot
      })
    })
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 上拉加载
    loadMore() {
      if (!this.data.q || this.isLocked()) {
        return
      }
      if (this.hasMore()) {
        this.locked()
        bookModel.search(this.getCurrentStart(), this.data.q)
          .then(res => {
            this.setMoreData(res.books)
            this.unLocked()
          }, () => {
            this.unLocked
          })
      }
    },

    // 搜索事件
    onConfirm(event) {
      const q = event.detail.value || event.currentTarget.dataset.text
      if (q === this.data.q) {
        return
      }
      this.initialize()
      this._showResult()
      this._showLoadingCenter()
      bookModel.search(0, q).then(res => {
        this.setData({
          q
        })
        this.setMoreData(res.books)
        this.setTotal(res.total)
        keywordModel.addToHistory(q)
        this._hideLoadingCenter()
      })
    },

    // 关闭搜索界面
    onCancel(event) {
      this.initialize()
      this.triggerEvent('cancel', {})
    },

    // 关闭搜索结果
    onDelete() {
      this.initialize()
      this._closeResult()
    },

    // 显示中间加载
    _showLoadingCenter() {
      this.setData({
        loadingCenter: true
      })
    },

    // 隐藏中间加载
    _hideLoadingCenter() {
      this.setData({
        loadingCenter: false
      })
    },

    // 显示搜索结果
    _showResult() {
      this.setData({
        searching: true
      })
    },

    // 关闭搜索结果
    _closeResult() {
      this.setData({
        searching: false,
        q: ''
      })
    }
  }
})